package data.platform.common.domain;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;

@Getter
@Setter
@Builder
@Slf4j
public class MetricValue {

    private String metric;

    /**
     * 一个SortedMap,转换成string
     */
    private Map<String, String> tag;

    private LocalDateTime eventTime;

    private Double value;
//    事件值
    private String eventValue;

    private String tagJson;

    public String getTagJson() {
        if(Objects.isNull(tagJson)) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                Map<String, String> sortedMap = new TreeMap<>();
                sortedMap.putAll(tag);
                tagJson = objectMapper.writeValueAsString(sortedMap);
            } catch (Exception ex) {
                log.error("", ex);
                tagJson = "";
            }
        }
        return tagJson;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        MetricValue that = (MetricValue) o;
        return Objects.equals(metric, that.metric) && Objects.equals(tag, that.tag) && Objects.equals(eventTime, that.eventTime);
    }

    @Override
    public int hashCode() {
        return Objects.hash(metric, tag, eventTime);
    }

    @Override
    public String toString() {
        return "MetricValue{" +
                "metric='" + metric + '\'' +
                ", tag=" + tag +
                ", eventTime=" + eventTime +
                '}';
    }
}
